/****************************************************************
 *  ColumnPicker
 *  Author: Felix Woo
 *  Date: 11-05-2007
 *
 *  How to use
 *  1. Load this component GUI file
 *     var cp = tibco.admin.Main.getServer().getBodyBlock().load("columnPicker.xml");
 *  2. Initialize, specify the GUI object which trigers this ColumnPicker and the matrix name which is handled by this control.
 *     cp.initialize(obj,"mtxDemo");
 ****************************************************************/

jsx3.Class.defineClass(
  "com.gix.gui.ColumnPicker",
  jsx3.gui.Block,
  null,
  function(control) {
    control.prototype.init = function(strName,vntLeft,vntTop,vntWidth,vntHeight,strHTML) {
      this.jsxsuper(strName,vntLeft,vntTop,vntWidth,vntHeight,strHTML);
        this.setDisplay(jsx3.gui.Block.DISPLAYNONE, false);
    }
    /**
     * Initialize the ColumnPicker control
     * @param obj {GUI object} It is the GUI object which trigers this ColumnPicker, and the ColumnPicker attachs to it.
     * @param mtxName {String} It is the name of the matrix which is handled by this ColumnPicker, ColumnPicker gets columns data from it.
     */
    control.prototype.initialize = function(obj, mtx, listUneditableCols, listExcludedCols) {
        this.parentButton = obj;
      if(!mtx) {
        this.actuallyClose();
      }
      //Delete other instances.
      var instances = tibco.admin.Main.getServer().getRootBlock().getDescendantsOfType("com.gix.gui.ColumnPicker",true);
      for (var i=0; i<instances.length; i++) {
        if(instances[i]!=this) {
          instances[i].actuallyClose();
        }
      }
      this.mtxColumnsHash = new Object();
      this.list = this.getDescendantOfName("mtxColumnPicker");
      this.setMtxTarget(mtx, listUneditableCols, listExcludedCols);
      //If the martix does not have any column, close this.
      if(this.mtxColumns.length==0) {
        this.actuallyClose();
      }
      //Set height accroding to the items count.
      var height = this.mtxColumns.length*20+2;
      var bbPos = tibco.admin.Main.getServer().getRootBlock().getAbsolutePosition();
      var position = obj.getAbsolutePosition();
      var bY = position.T + (position.H / 2);
      var bX = position.L + (position.W / 2);
      var spaceAbove = bY;
      var posTop = spaceAbove;
      var renderBelow = true;
      var spaceBelow = bbPos.H - spaceAbove;
      if(height > spaceBelow - 5) {
          if(height < spaceAbove - 5) {
              renderBelow = false;
              posTop = bY - height;
          }
          else {
              renderBelow = (spaceBelow > spaceAbove);
              height = renderBelow ? (spaceBelow - 5) : (spaceAbove - 5);
              if(!renderBelow) {
                  posTop = bY - height;
              }
              this.list.setSuppressVScroller(0,false);
              this.setMargin("0 25 0 0");
          }
      }
      this.setHeight(height,true);
      var posLeft = bX;
      if((posLeft+this.getWidth()) > (bbPos.W - 5)) {
        posLeft = bX - this.getWidth();
      }
      this.setLeft(posLeft, false);
      this.setTop(posTop, true);
        this.setDisplay(jsx3.gui.Block.DISPLAYBLOCK, true);
        this.list.repaint();
        var me = this;
        this.closeIds = new jsx3.util.List(0);
      jsx3.gui.Event.subscribe(jsx3.gui.Event.MOUSEOUT, me, me.close);
        jsx3.gui.Event.subscribe(jsx3.gui.Event.MOUSEOVER, me, me.cancelClose);
    }

      control.prototype.cancelClose = function(objEvent) {
          if(jsx3.html.getJSXParent(objEvent.event.toElement()) == this.list) {
          this.closeIds.removeAt(0);
          this.haveEntered = true;
          this.shouldClose = false;
          }
      }

    /**
     * Close this ColumnPicker
     */
    control.prototype.close = function(objEvent) {
        if(jsx3.html.getJSXParent(objEvent.event.fromElement()) == this.list) {
        if(!this.haveEntered || this.shouldClose) return;
            this.shouldClose = true;
        var me = this;
        var closeId = jsx3.xml.CDF.getKey();
        me.closeIds.add(closeId);
        setTimeout(function() {
            me.attemptClose(closeId);
        },500);
        }
    }

    control.prototype.attemptClose = function(id) {
        if(this.shouldClose && this.closeIds.contains(id)) {
            this.actuallyClose();
        }
    }

      control.prototype.actuallyClose = function() {77777777777777777777777
          jsx3.gui.Event.unsubscribe(jsx3.gui.Event.MOUSEOUT, this);
          jsx3.gui.Event.unsubscribe(jsx3.gui.Event.MOUSEOVER, this);
         this.list.setSuppressVScroller(1,false);
         this.getParent().removeChild(this);
         this.shouldClose = false;
          this.closeIds.clear();
          this.parentButton.columnPickerClosed(this);
      }

    /**
     * Set the matrix target which is handled by this ColumnPicker.
     */
    control.prototype.setMtxTarget = function(mtx, listUneditableCols, listExcludedCols) {
//      this.mtxName = mtxName;
//        if(mtx instanceof jsx3.gui.Matrix) {
            this.mtxTarget = mtx;
            this.uneditableCols = listUneditableCols ? listUneditableCols : new jsx3.util.List(0);
            this.excludedCols = listExcludedCols ? listExcludedCols : new jsx3.util.List(0);
//        }
//        else {
//            this.mtxTarget = tibco.admin.Main.getServer().getJSXByName(this.mtxName);
//        }
        this.mtxColumns = new Array();
        this.origStates = new Object();
      var tmpCols = this.mtxTarget.getChildren();
      this.list.getXML().removeChildren();
      for (var i=0; i<tmpCols.length; i++) {
          var id = tmpCols[i].getId();
          var display = tmpCols[i].getDisplay() != jsx3.gui.Block.DISPLAYNONE;
          this.origStates[id] = display;
          if(!this.excludedCols.contains(id)) {
        var record = this.list.getXML().createNode(jsx3.xml.Entity.TYPEELEMENT, "record", "");
        var colText = this.getColumnText(tmpCols[i]);
        record.setAttribute("jsxid", id);
        record.setAttribute("columnName", colText);
        record.setAttribute("selected", display);
        if(this.uneditableCols.contains(id)) {
            record.setAttribute("jsxdisabled","1");
        }
        this.mtxColumns.push(tmpCols[i]);
        this.mtxColumnsHash[id]=tmpCols[i];
        this.list.getXML().appendChild(record);
      }
      }
      this.list.repaint();
    }

      control.prototype.getChangedColumns = function() {
          var allCols = this.mtxTarget.getChildren();
          var removed = new Array();
          var added = new Array();
          for (var i=0; i<allCols.length; i++) {
              var id = allCols[i].getId();
              var display = allCols[i].getDisplay() != jsx3.gui.Block.DISPLAYNONE;
              if(display != this.origStates[id]) {
                  ((display) ? added : removed).push(id);
              }
          }
          var ret = new Object();
          ret.added = added;
          ret.removed = removed;
          return ret;
      }

      control.prototype.getColumnText = function(col) {
          var text = col.getText();
          if(!text) {
              var dp = col.getDynamicProperty("jsxtext");
              if(dp) {
                  text = tibco.admin.Main.getServer().getDynamicProperty(dp);
                  if(!text) {
                      text = "";
                  }
              }
          }
          return text;
      }

    /**
     * Event handler for select
     */
    control.prototype.onSelectList = function(id) {
      var node = this.list.getXML().selectSingleNode("//record[@jsxid='"+id+"']");
      if(this.uneditableCols.contains(id)) {
          return;
      }
      var selected = node.getAttribute("selected");
      if(selected!="true") {
        selected="true";
      } else {
        selected="false";
      }
      node.setAttribute("selected",selected);
      this.list.repaint();
      if(this.mtxColumns) {
        this.displayHideColumn(node);
      }
    }

    /**
     * Event handler for drag&drop
     */
    control.prototype.onChangeOrder = function(strDRAGIDS,strRECORDID) {
//      var nodeSource = this.list.getXML().selectSingleNode("//record[@jsxid='"+strDRAGIDS[0]+"']");
//      var nodeTarget = this.list.getXML().selectSingleNode("//record[@jsxid='"+strRECORDID+"']");
      this.mtxTarget.insertBefore(this.mtxColumnsHash[strDRAGIDS[0]],
                                  this.mtxColumnsHash[strRECORDID],
                                  true);
    }

    /**
     * Set the column Display/Hide
     */
    control.prototype.displayHideColumn = function(node) {
      var display = node.getAttribute("selected")=="true" ? jsx3.gui.Block.DISPLAYBLOCK : jsx3.gui.Block.DISPLAYNONE;
      this.mtxColumnsHash[node.getAttribute("jsxid")].setDisplay(display, true);
        this.mtxTarget.repaintData();
    }

    /**
     * Repaint the target matrix according to changes.
     *
     * IT IS USELESS!
     */
    control.prototype.repaintMtxTarget = function() {
      this.mtxTarget.removeChildren();
      var iter = this.list.getXML().getChildIterator();
      while(iter.hasNext()) {
        var col = iter.next();
        var display = col.getAttribute("selected")=="true" ? jsx3.gui.Block.DISPLAYBLOCK : jsx3.gui.Block.DISPLAYNONE;
        this.mtxColumnsHash[col.getAttribute("jsxid")].setDisplay(display, false);
        this.mtxTarget.setChild(this.mtxColumnsHash[col.getAttribute("jsxid")]);
      }
      this.mtxTarget.repaint();
    }
  }
);